'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview  联盟任务系统
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var unionMissionConf = require('../../../../config/unionMissionConf.js');
var unionGroupModel = require('../../../../models/unionGroupModel');
var unionPositionType = require('../../../../consts/unionPositionType');
var PlayerManager = require('../../../../libs/playerManager');
var roleService = require('../../../../services/roleService');
var constantUtil = require('../../../../util/constantUtil.js');
var rewardService = require('../../../../services/rewardService.js');

/**
 * 开始任务
 */

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var star = msg.star;
    var reward_list;
    var union_task_list = [];
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                ['role', 'unionTask', 'bag', 'vip', 'build', 'soldier', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var unionTask_model = player_manager.unionTask;

                // 是否达到领取条件
                if (unionTask_model.total_star < star) {
                    return next(null, {
                        code: Code.UNION_NOT_STARBOXRECEIVE
                    });
                }
                // 是否领取过奖励   没有领取过则加入记录
                if (!unionTask_model.addStarRecord(star)) {
                    return next(null, {
                        code: Code.UNION_NOT_RECEIVE_UNIONTASK
                    });
                }

                // 发放奖励
                reward_list = unionMissionConf.unionBox(star) || [];
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_UNION, operationType.OPR_UNION_TASK_REWARD);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};
